package org.example.clouddemo.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import org.example.clouddemo.bean.common.entity.User;
import org.example.clouddemo.service.common.UserService;
import org.example.common.response.ApiResult;
import org.example.common.response.ApiResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 * 用户表 内部接口
 * </p>
 * 对于管理后台的接口
 *
 * @author hzg
 * @since 2025-06-06
 */

@RestController
@RequestMapping("/api/admin/user")
public class UserController {

    @Autowired
    public UserService userService;

    @PostMapping("list/{page}/{pageSize}")
    public ApiResult list(@PathVariable("page") int page, @PathVariable("pageSize") int pageSize) {
        Page pageInfo = new Page<>();
        pageInfo.setCurrent(page);
        pageInfo.setSize(pageSize);
        IPage result = userService.selectPageVo(pageInfo);
        return ApiResult.success(result);
    }

    @PostMapping("queryOne")
    public ApiResult queryOne(@RequestParam("username") String username) {
        return ApiResult.success(userService.selectOne(username));
    }


    @PostMapping("delete/{id}")
    public ApiResult delete(@PathVariable("id") Long id,
                            @RequestParam("flag") Boolean flag) {
        return ApiResult.success(userService.delete(id,flag));
    }

    @PostMapping("update")
    public ApiResult update(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getId())) {
            return ApiResult.res(ApiResultCode.PARAMS_NOT_EXIST);
        }
        return ApiResult.success(userService.update(user));
    }

    @ApiOperation(value = "修改用户头像", notes = "需要token")
    @ApiOperationSupport(order = 5)
    @PostMapping("updateAvatar")
    public ApiResult<Boolean> updateAvatar(@RequestParam("file") MultipartFile file,
                                           HttpServletRequest request) {

        // 调用 userService 方法处理头像更新
        Boolean result = userService.updateAvatar(file,request);

        return ApiResult.success(result);
    }

    @ApiOperation(value = "修改用户昵称", notes = "需要token")
    @ApiOperationSupport(order = 6)
    @PostMapping("updateNickname")
    public ApiResult<Boolean> updateNickname(@RequestParam("nickname") String nickname) {
        Boolean result = userService.updateNickname(nickname);

        return ApiResult.success(result);
    }

}
